package com.platform.util.sms;


import com.alibaba.fastjson.JSONObject;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.platform.utils.ResourceUtil;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.*;

import java.io.IOException;

/**
 * Created by ddw on 2017/7/3/003.
 */
public class SmsUtils {

    private static Logger logger = LoggerFactory.getLogger(SmsUtils.class);

    private static String baseUrl = ResourceUtil.getConfigByName("sms.baseUrl");
    public static final String acount= ResourceUtil.getConfigByName("sms.acount");
    public static final String secret = ResourceUtil.getConfigByName("sms.secret");
//    private static String baseUrl = Global.getConfig("captcha.baseUrl");
//    public static final String acount = Global.getConfig("captcha.account");
//    public static final String secret = Global.getConfig("captcha.secret");


    private static Retrofit retrofitCaptcha = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create(genericGson()))
            .client(genericClient())
            .build();

    private static Gson genericGson(){
        Gson gson = new GsonBuilder()
                .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                .create();
        return gson;
    }

    public static OkHttpClient genericClient() {
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request request = chain.request()
                                .newBuilder()
                                .addHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8")
                                .addHeader(HttpHeaders.AUTHORIZATION, getHeaderAuthorization())
                                //.addHeader("Accept-Encoding", "gzip, deflate")
                                //.addHeader("Connection", "keep-alive")
                                //.addHeader("Accept", "*/*")
                                //.addHeader("Cookie", "add cookies here")
                                .build();
                        return chain.proceed(request);
                    }
                }).build();
        return httpClient;
    }


    public static String getHeaderAuthorization() {
        String token = Base64.encodeBase64String((acount + ":" + secret).getBytes());
        String headerAuthorization = "Basic " + token;
        return headerAuthorization;
    }

    /**
     * 发送验证码
     * @param mobileNo
     * @return
     */
    public static Object deliver(String mobileNo){
        SmsService captachService = retrofitCaptcha.create(SmsService.class);
        Response response = null;
        Call<JSONObject> call = captachService.captchaDeliver(mobileNo);
        try {
            response = call.execute();
            if (response != null && response.body() != null){
                return response.body();
            } else {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
           return null;
        }
    }


    /**
     * 验证验证码
     * @param mobileNo
     * @param captcha
     * @return
     */
    public static Object  verify(String mobileNo,String captcha){
        SmsService captachService = retrofitCaptcha.create(SmsService.class);
        Response response = null;
        Call<JSONObject> call = captachService.verify(mobileNo,captcha);
        try {
            response = call.execute();
            if (response != null && response.body() != null){
                return response.body();
            } else {
                return null;
            }
        } catch (IOException e) {
            return null;
        }
    }



    /**
     * 发送内容
     * @param mobileNo
     * @return
     */
    public static Object deliver(String mobileNo, String content){
        SmsService captachService = retrofitCaptcha.create(SmsService.class);
        Response response = null;
        Call<JSONObject> call = captachService.deliver(mobileNo, content);
        try {
            response = call.execute();
            if (response != null && response.body() != null){
                return response.body();
            } else {
                return null;
            }
        } catch (IOException e) {
            return null;
        }
    }


    private interface SmsService {

        @GET("/v1/captcha/deliver")
        Call<JSONObject> captchaDeliver(@Query("mobileNo") String mobileNo);

        @GET("/v1/captcha/verify")
        Call<JSONObject> verify(@Query("mobileNo") String mobileNo, @Query("captcha") String captcha);

        @POST("/v1/deliver")
        @FormUrlEncoded
        Call<JSONObject> deliver(@Field("mobileNo") String mobileNo, @Field("content") String content);

        @POST("/v1/sendEmail")
        Call<JSONObject> sendEmail(@Body okhttp3.RequestBody parameter);
    }
}
